# 主要是练习装饰器,和多线程,多进程的使用

# 使用装饰器增强完成1-999999所有奇数和计算10次
#    1.使用普通方法
#    2.使用多线程
#    3.使用多进程
#    4.采用线程池完成计算
#    5.采用进程池完成计算
from multiprocessing import Process
from threading import Thread
from time import time
from multiprocessing import Process,Pool,cpu_count  #进程池对象
from multiprocessing.dummy import Pool as threadpool  #线程池对象
#普通方法
def time_1(func):
    def internal():
        time1 = time()
        func()
        time2 = time()
        print('总消耗时间',time2-time1)
        print('#'* 44)
    return internal
@time_1
def ordinary1():
    for i in range(10):
        sum((range(1,999999,2)))
def ordinary():
    sum((range(1,999999,2)))
#多进程
@time_1
def process_list():
    process = [Process(target=ordinary,args=()) for i in range(0,10)]
    for pro in process:
        pro.start()
        pro.join()

#多线程
@time_1
def thread_list():
    for i in range(10):
        thread = Thread(target=ordinary,args=())
        thread.start()
        thread.join()


#线程池
@time_1
def thread_pool():
    list1 = list(range(0,10))
    pool = threadpool(cpu_count())
    pool.map_async(ordinary,list1)      #map_async开启池 第二个参数是序列对象,开启多少个线程对象
    pool.close()
    pool.join()
#进程池
@time_1
def process_pool():
    pool = Pool(cpu_count())
    for i in range(10):
        pool.apply_async(ordinary,())  #apply_async  开启池 第二个是元组参数,传递给前面的function对象
    pool.close()
    pool.join()

if __name__ == '__main__':
    process_list()
    thread_list()
    ordinary1()
    thread_pool()
    process_pool()

